﻿using System;
using System.Collections.Generic;
using System.Linq;
using VASJ.Model.Helper;
using System.ComponentModel;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using VASJ.Business;
using VASJ.Model;
using VASJ.Common;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;

namespace VASJ.Presentation.HeThong
{
    public partial class FrmCapNhatNguoiSudung : DevExpress.XtraEditors.XtraForm
    {
        #region Properties
        private readonly UserViewModel currentUserViewModel;
        private readonly bool isNew;
        private Organization selectedOrg;
        #endregion

        #region Events
        public FrmCapNhatNguoiSudung(UserViewModel userModel)
        {
            InitializeComponent();

            currentUserViewModel = userModel;
            isNew = currentUserViewModel == null;
            if(isNew) currentUserViewModel = new UserViewModel();

            //LoadResource();
            LoadUser();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                var user = CreateUserViewModel();
                UserService.SubmitUser(user);
            }
        }

        //private void tvUnit_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
        //{
        //    SetEditFromTree();
        //}

        //private void tvUnit_DoubleClick(object sender, EventArgs e)
        //{
        //    SetEditFromTree();

        //    // close the popup
        //    PopupContainerEdit editor = GetParentEditor(sender as System.Windows.Forms.Control);
        //    if (editor != null)
        //        editor.ClosePopup();
        //}
        #endregion

        #region Methods
        private void LoadResource()
        {
            btnSave.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.btnSave", "vi-VN");
            btnCancel.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.btnCancel", "vi-VN");

            lblSQLUser.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblSQLUser", "vi-VN");
            lblAlias.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblAlias", "vi-VN");
            lblUserName.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblUserName", "vi-VN");
            lblFullName.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblFullName", "vi-VN");
            lblPassword.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblPassword", "vi-VN");
            lblRepeatPassword.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblRepeatPassword", "vi-VN");
            lblDepartment.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblDepartment", "vi-VN");
            chkInternetAccess.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.chkInternetAccess", "vi-VN");
            chkIntranetAccess.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.chkIntranetAccess", "vi-VN");
            chkIsManager.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.chkIsManager", "vi-VN");
            lblInheritance.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblInheritance", "vi-VN");
            lblUnit.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.lblUnit", "vi-VN");

            if(isNew)
                this.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.Title-New", "vi-VN");
            else
                this.Text = ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.Title-Edit", "vi-VN");
        }

        public void LoadUser()
        {
            LoadLookUpEdit();
            LoadUnitTree();
          
            if (!isNew)
            {
                BindData(currentUserViewModel);
            }
        }

        private void LoadUnitTree()
        {
            var listOrg = DALHelper.GetAllOrganizations();

            tlOrganizer.BeginUnboundLoad();
            TreeListNode rootNodes = null;
            TreeListNode theFirstNode = null;

            foreach (var org in listOrg)
            {
                TreeListNode rootNode = tlOrganizer.AppendNode(new object[] { org.Name}, rootNodes,org);
              
                // Create a child of the rootNode
                List<Organization> unitInfoList = DALHelper.GetCompaniesByParent(org.Id);
                foreach (var childOgr in unitInfoList)
                {
                    tlOrganizer.AppendNode(new object[] { org.Name }, rootNode,childOgr);
                }

                if (theFirstNode == null)
                    theFirstNode = rootNode;
            }
            
            tlOrganizer.EndUnboundLoad();

            tlOrganizer.SetFocusedNode(theFirstNode);
            PopupContainerEdit editor = GetParentEditor(tlOrganizer);
            if (editor != null && theFirstNode.Tag != null)
                editor.EditValue = ((Organization)theFirstNode.Tag).Name ?? "";
        }

        private void LoadLookUpEdit()
        {
            var SQLUsers = SQLUserService.GetAll();
            lueSQLUser.Properties.DataSource = lueInheritance.Properties.DataSource = null;
            lueSQLUser.Properties.DataSource = lueInheritance.Properties.DataSource = SQLUsers;
            lueSQLUser.Properties.ValueMember = lueInheritance.Properties.ValueMember = ComboBoxHelper.ValueMember;
            lueSQLUser.Properties.DisplayMember = lueInheritance.Properties.DisplayMember = ComboBoxHelper.DisplayMember;
            lueSQLUser.Properties.PopulateColumns();
            lueInheritance.Properties.PopulateColumns();
            if (SQLUsers.Count > 0)
            {
                lueSQLUser.EditValue = lueInheritance.EditValue = SQLUsers.FirstOrDefault().Id;
                lueSQLUser.Enabled = lueInheritance.Enabled = true;
            }
            else
            {
                lueSQLUser.Enabled = lueInheritance.Enabled = false;
            }
        }

        private void BindData(UserViewModel user)
        {
            lueSQLUser.EditValue = user.SQLUser;
            txtAlias.Text = user.Alias;
            txtUserName.Text = user.UserName;
            txtFullName.Text = user.FullName;
            txtPassword.Text = user.Password;
            txtRepeatPassword.Text = user.Password;
            txtDepartment.Text = user.Department;
            chkInternetAccess.Checked = user.IsInternetAccess;
            chkIntranetAccess.Checked = user.IsIntranetAccess;
            chkIsManager.Checked = user.IsManager;
            lueSQLUser.EditValue = user.Inheritance;
        }

        private bool IsValidate()
        {
            if (Validation.IsInvalidString(txtAlias.Text)) 
            {
                errorProvider.SetError(txtAlias,ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.AliasIsRequired", "vi-VN"));
                txtAlias.Focus();
                return false;
            }
            if (Validation.IsInvalidString(txtUserName.Text))
            {
                errorProvider.SetError(txtUserName, ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.UserNameIsRequired", "vi-VN"));
                txtUserName.Focus();
                return false;
            }
            if (Validation.IsInvalidString(txtFullName.Text))
            {
                errorProvider.SetError(txtFullName, ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.FullNameIsRequired", "vi-VN"));
                txtFullName.Focus();
                return false;
            }
            if (Validation.IsInvalidString(txtPassword.Text))
            {
                errorProvider.SetError(txtPassword, ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.PasswordIsRequired", "vi-VN"));
                txtPassword.Focus();
                return false;
            }
            if (Validation.IsInvalidString(txtRepeatPassword.Text))
            {
                errorProvider.SetError(txtRepeatPassword, ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.RepeatPasswordIsRequired", "vi-VN"));
                txtRepeatPassword.Focus();
                return false;
            }
            if (Validation.IsInvalidString(txtDepartment.Text))
            {
                errorProvider.SetError(txtDepartment, ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.DepartmentIsRequired", "vi-VN"));
                txtDepartment.Focus();
                return false;
            }
            if (!txtPassword.Text.Equals(txtRepeatPassword.Text))
            {
                errorProvider.SetError(txtRepeatPassword, ResourceManager.GetResourceTitle("FrmCapNhatNguoiSudung.RepeatPasswordIsTheSamePassword", "vi-VN"));
                txtRepeatPassword.Focus();
                return false;
            }

            return true;
        }

        private UserViewModel CreateUserViewModel()
        {
            var userModel = new UserViewModel()
            {
                SQLUser = (int)lueSQLUser.EditValue,
                Alias = txtAlias.Text,
                UserName = txtUserName.Text,
                FullName = txtFullName.Text,
                Password = txtPassword.Text,
                Department = txtDepartment.Text,
                IsInternetAccess = chkInternetAccess.Checked,
                IsIntranetAccess = chkIntranetAccess.Checked,
                IsManager = chkIsManager.Checked,
                Inheritance = (int)lueSQLUser.EditValue,
                Unit = selectedOrg.Id
            };

            if (!isNew) userModel.Id = currentUserViewModel.Id;

            return userModel;
        }

        static PopupContainerControl GetParentContainer(TreeList ctrl)
        {
            if (ctrl == null)
                return null;
            return ctrl.Parent as PopupContainerControl;
        }

        static PopupContainerEdit GetParentEditor(TreeList ctrl)
        {
            PopupContainerControl container = GetParentContainer(ctrl);
            return container == null ? null : container.OwnerEdit;
        }

        private void tlOrganizer_DoubleClick(object sender, EventArgs e)
        {
            PopupContainerEdit editor = GetParentEditor(tlOrganizer);
            if (editor == null)
                    return;
            editor.EditValue = selectedOrg.Name ?? "";
        }

        private void tlOrganizer_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            if (e.Node.Tag != null)
                selectedOrg = (Organization)e.Node.Tag;
        }
        
        #endregion
    }
}